const cacheService = require('../cache/cacheService');
const cacheMonitor = require('../cache/utils/cacheMonitor');
const { getLogger } = require('../logger');
const { success, badRequest, serverError, notFound } = require('../utils/response');
const { validateRequired } = require('../utils/validator');

const logger = getLogger('controllers.cacheController');

/**
 * 获取缓存列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getCacheList = async (req, res) => {
    try {
        // 获取查询参数
        const { search, page = 1, pageSize = 100 } = req.query;
        const pageNum = parseInt(page) || 1;
        const size = parseInt(pageSize) || 100;
        
        // 获取所有缓存键
        const allKeys = await cacheService.getAllKeys();
        
        // 获取缓存类型信息
        const cacheType = cacheService.getProviderType();
        
        // 获取缓存统计信息
        const cacheStats = cacheMonitor.getStats();
        
        // 过滤缓存键（如果提供了搜索条件）
        let filteredKeys = allKeys;
        if (search) {
            const searchLower = search.toLowerCase();
            filteredKeys = allKeys.filter(key => 
                key.toLowerCase().includes(searchLower)
            );
        }
        
        // 计算分页
        const start = (pageNum - 1) * size;
        const end = start + size;
        const paginatedKeys = filteredKeys.slice(start, end);
        
        success(req, res, '获取缓存列表成功', {
            data:paginatedKeys,
            cacheType:cacheType,
            stats:cacheStats,
            pagination: {
                page:pageNum,
                limit:size,
                total:filteredKeys.length,
                pages: Math.ceil(filteredKeys.length / size)
            }
        });
    } catch (error) {
        logger.error('获取缓存列表失败', { error: error });
        serverError(req, res, '获取缓存列表失败');
    }
};

/**
 * 删除指定缓存
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const deleteCache = async (req, res) => {
    try {
        const { key } = req.params;
        
        if (!key) {
            return badRequest(req, res, '缓存键不能为空');
        }
        
        const result = await cacheService.del(key);
        
        if (result) {
            logger.info('缓存删除成功', { key });
            success(req, res, '缓存删除成功', { key });
        } else {
            logger.warn('缓存删除失败', { key });
            notFound(req, res, '缓存不存在或删除失败');
        }
    } catch (error) {
        logger.error('删除缓存失败', { error: error });
        serverError(req, res, '删除缓存失败');
    }
};

/**
 * 批量删除缓存
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const batchDeleteCache = async (req, res) => {
    try {
        const { keys } = req.body;
        
        if (!Array.isArray(keys) || keys.length === 0) {
            return badRequest(req, res, '请提供有效的缓存键数组');
        }
        
        const result = await cacheService.mdel(keys);
        
        if (result) {
            logger.info('批量删除缓存成功', { count: keys.length });
            success(req, res, `成功删除 ${keys.length} 个缓存项`, { deletedCount: keys.length });
        } else {
            logger.warn('批量删除缓存失败');
            serverError(req, res, '批量删除缓存失败');
        }
    } catch (error) {
        logger.error('批量删除缓存失败', { error: error });
        serverError(req, res, '批量删除缓存失败');
    }
};

/**
 * 根据模式清除缓存
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const clearByPattern = async (req, res) => {
    try {
        const { pattern } = req.params;
        
        if (!pattern) {
            return badRequest(req, res, '清除模式不能为空');
        }
        
        const deletedCount = await cacheService.clearByPattern(pattern);
        
        logger.info('根据模式清除缓存成功', { pattern, deletedCount });
        success(req, res, `成功清除 ${deletedCount} 个缓存项`, { pattern, deletedCount });
    } catch (error) {
        logger.error('根据模式清除缓存失败', { error: error });
        serverError(req, res, '根据模式清除缓存失败');
    }
};

/**
 * 获取缓存统计信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getCacheStats = async (req, res) => {
    try {
        const stats = cacheMonitor.getStats();
        const cacheType = cacheService.getProviderType();
        
        const responseData = {
            cacheType,
            stats
        };
        
        success(req, res, '获取缓存统计信息成功', responseData);
    } catch (error) {
        logger.error('获取缓存统计信息失败', { error: error });
        serverError(req, res, '获取缓存统计信息失败');
    }
};

/**
 * 重置缓存统计信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const resetCacheStats = async (req, res) => {
    try {
        cacheMonitor.resetStats();
        
        logger.info('缓存统计信息已重置');
        success(req, res, '缓存统计信息已重置');
    } catch (error) {
        logger.error('重置缓存统计信息失败', { error: error });
        serverError(req, res, '重置缓存统计信息失败');
    }
};

module.exports = {
    getCacheList,
    deleteCache,
    batchDeleteCache,
    clearByPattern,
    getCacheStats,
    resetCacheStats
};